package com.gt.xmall.util;

import java.sql.Types;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;





public class RequestUtil {
	public static CommonRecord toCommonRecord(CommonRecord crm,HttpServletRequest request, int jdbcType, String charsetFrom, String charsetTo) {
		String value = "";
		String name = "";
//		CommonRecord crm = new CommonRecord();
		if(crm ==null){
			crm = new CommonRecord();
		}
		CustomField field = null;
		java.util.Enumeration names = request.getParameterNames();
		while (names.hasMoreElements()) {
			name = (String) names.nextElement();
			//value = wc.getParameter(name, charsetFrom, charsetTo);
			value = StringUtil.replaceSpecialChars(StringUtil.convertCharset(StringUtils.trim(request.getParameter(name)), charsetFrom, charsetTo));
			field = new CustomField(name, jdbcType, value);
			crm.addField(field);
		}
		return crm;
	}
	public static CommonRecord toCommonRecord(CommonRecord crm,HttpServletRequest request) {
		return toCommonRecord(crm,request, Types.VARCHAR, "UTF-8", "UTF-8");
	}
	public static CommonRecord toCommonRecord(HttpServletRequest request, int jdbcType, String charsetFrom, String charsetTo) {
		String value = "";
		String name = "";
		CommonRecord crm = new CommonRecord();
		CustomField field = null;
		java.util.Enumeration names = request.getParameterNames();
		while (names.hasMoreElements()) {
			name = (String) names.nextElement();
			//value = wc.getParameter(name, charsetFrom, charsetTo);
			value = StringUtil.replaceSpecialChars(StringUtil.convertCharset(StringUtils.trim(request.getParameter(name)), charsetFrom, charsetTo));
			field = new CustomField(name, jdbcType, value);
			crm.addField(field);
		}
		return crm;
	}

	public static CommonRecord toCommonRecord(HttpServletRequest request) {
		return toCommonRecord(request, Types.VARCHAR, "UTF-8", "UTF-8");
	}
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
}
